<template>
  <a-card :bordered="false">
    <div class="table-operator">
      <a-button v-if="hasPerm('Base_User.Add')" type="primary" icon="plus" @click="handleAdd()">新建</a-button>
      <a-button
        v-if="hasPerm('Base_User.Delete')"
        type="primary"
        icon="minus"
        @click="handleDelete(selectedRowKeys)"
        :disabled="!hasSelected()"
        :loading="loading"
      >删除
      </a-button>
      <a-button type="primary" icon="redo" @click="getDataList()">刷新</a-button>
    </div>

    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="6" :sm="24">
            <a-form-item
              label="姓名">
              <a-input v-model="queryParam.keyword" placeholder @keydown.enter="getDataList"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-button
              type="primary"
              @click="
                () => {
                  this.pagination.current = 1
                  this.getDataList()
                }">查询
            </a-button>
            <a-button style="margin-left: 8px" @click="() => (queryParam = {})">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <a-table
      ref="table"
      :scroll="{ y: tableHeight }"
      :columns="columns"
      :rowKey="(row, index) => row.Id"
      :dataSource="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :bordered="true"
      size="small"
    >
      <span slot="UserAvatarURL" slot-scope="text, record">
        <a v-if="hasPerm('Base_User.Edit')" @click="UploadFile(record.Id)">
          <a-popover>
            <!-- <img :src="text" @error="this.src = null" width="30px" height="30px" /> -->
            <a-avatar icon="user" :src="text" style="width: 30px;height: 30px;" />
            <template #content>
              <a-avatar icon="user" :src="text" :size="200" style="width: 200px;height: 200px;" />
            </template>
          </a-popover>
        </a>
        <a v-if="!hasPerm('Base_User.Edit')">
          <a-popover>
            <!-- <img :src="text" @error="this.src = null" width="30px" height="30px" /> -->
            <a-avatar icon="user" :src="text" style="width: 30px;height: 30px;" />
            <template #content>
              <a-avatar icon="user" :src="text" :size="200" style="width: 200px;height: 200px;" />
            </template>
          </a-popover>
        </a>
      </span>
      <span slot="action" slot-scope="text, record">
        <template>
          <template v-if="hasPerm('Base_User.Edit')">
            <a @click="handleEdit(record.Id)">编辑</a>
            <a-divider type="vertical" />
          </template>

          <a v-if="hasPerm('Base_User.Delete')" @click="handleDelete([record.Id])">删除</a>
          <a-divider type="vertical" />
          <a @click="openCodeRule(record.Id)">组织权限</a>
        </template>
      </span>
    </a-table>
    <edit-form ref="editForm" :afterSubmit="getDataList"></edit-form>
    <departmentList ref="DepartmentList" :parentObj="this"></departmentList>
    <UploadPictureForm
      ref="uploadPicture"
      leading="/Base_Manage/Base_User/UploadFileByForm"
      :parent-obj="this"
      :max-count="1"
    ></UploadPictureForm>
  </a-card>
</template>

<script>
import EditForm from './EditForm'
import UploadPictureForm from '@/components/FileOperations/UploadPictureForm'
import DepartmentList from './Base_UserDepartment.vue'
const columns = [
  { title: '头像', dataIndex: 'UserAvatarURL', width: '50px', scopedSlots: { customRender: 'UserAvatarURL' } },
  { title: '用户名', dataIndex: 'UserName', width: '10%' },
  { title: '姓名', dataIndex: 'RealName', width: '10%' },
  { title: '性别', dataIndex: 'SexText', width: '5%' },
  { title: '出生日期', dataIndex: 'BirthdayText', width: '10%' },
  { title: '手机号码', dataIndex: 'UserPhone', width: '10%' },
  { title: '所属部门', dataIndex: 'DepartmentName', width: '10%' },
  { title: '所属角色', dataIndex: 'RoleNames', width: '30%' },
  { title: '操作', dataIndex: 'action', scopedSlots: { customRender: 'action' }, width: '15%' }
]

export default {
  components: {
    EditForm,
    UploadPictureForm,
    DepartmentList
  },
  mounted () {
    this.$nextTick(() => {
      // 页面渲染完成后的回调
      this.tableHeight = this.getTableHeight(true) + 24
    })
    this.getDataList()
  },
  data () {
    return {
      tableHeight: 570, // 表格高度
      data: [],
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面啊可以通过下拉框进行选择
        showSizeChanger: true
      },
      filters: {},
      entityId: '',
      sorter: { field: 'CreateTime', order: 'desc' },
      loading: false,
      columns,
      queryParam: {},
      visible: false,
      selectedRowKeys: [],
      uploadFileURL: '',
      imgUrl: require('@/assets/logo.png')
    }
  },
  methods: {
    handleTableChange (pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }

      this.getDataList()
    },
    getDataList () {
      this.selectedRowKeys = []
      this.loading = true
      this.$http
        .post('/Base_Manage/Base_User/GetDataList', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: this.sorter.field || 'Id',
          SortType: this.sorter.order,
          Search: this.queryParam,
          ...this.filters
        })
        .then(resJson => {
          this.loading = false
          this.data = resJson.Data
          if (this.data) {
            const pagination = { ...this.pagination }
            pagination.total = resJson.Total
            this.pagination = pagination
          }
        })
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    hasSelected () {
      return this.selectedRowKeys.length > 0
    },
    handleAdd () {
      this.$refs.editForm.openForm('', '添加用户信息')
    },
    handleEdit (id) {
      this.$refs.editForm.openForm(id, '编辑用户信息')
    },
    openCodeRule (id) {
      this.$refs.DepartmentList.openDrawer(id)
    },
    handleDelete (ids) {
      const thisObj = this
      this.$confirm({
        title: '确认删除吗?',
        onOk () {
          return new Promise((resolve, reject) => {
            thisObj.submitDelete(ids, resolve, reject)
          }).catch(() => console.log('Oops errors!'))
        }
      })
    },
    submitDelete (ids, resolve, reject) {
      this.$http.post('/Base_Manage/Base_User/DeleteData', ids).then(resJson => {
        resolve()

        if (resJson.Success) {
          this.$message.success('操作成功!')

          this.getDataList()
        } else {
          this.$message.error(resJson.Msg)
        }
      })
    },
    UploadFile (id) {
      this.uploadFileURL = ''
      this.entityId = id
      this.$refs.uploadPicture.openForm('修改头像')
    },
    imgError (event) {
      const img = event.src
      img.src = null
      img.onerror = null // 防止闪图
      // return this.imgUrl
      // const img = event.src
      // img.src = this.imgUrl
      // img.onerror = null // 防止闪图
    },
    UpdateSaveFileUrl () {
      this.loading = true
      if (this.entityId) {
        this.queryParam = { Condition: 'UserAvatarURL', Keyword: this.uploadFileURL }
        this.$http
          .post('/Base_Manage/Base_User/UpdateDataByConditions', {
            Id: this.entityId,
            Search: this.queryParam
          })
          .then(resJson => {
            if (resJson.Success) {
              this.$message.success('头像地址保存成功!')
              this.queryParam = {}
              this.getDataList()
            } else {
              this.$message.error(resJson.Msg)
            }
          })
      }
      this.loading = false
    }
  }
}
</script>
